<template>
	<x-popup position="bottom" :show="showUpgrade" :closeIcon="false" @update:show="closeUpgrade">
		<view class="CouponBox" @click="CouponBoxClose">
			<view class="couponContent" @click.stop="">
				<view class="couponNav">
					<view class="couponNavItem" :class="couponIndex === index ? 'couponNavItemA' : ''"
						v-for="(v, index) in couponNav" :key="index" @click="couponNavChange(index)">
						<view class="text">{{ v }}</view>
						<view class="line"></view>
					</view>
				</view>
				<view v-if="couponIndex == '0'" class="couponList">
					<view class="couponItem couponItemcanbus" v-for="(item, index) in couponUseList" :key="index"
						@click="couponAct(index)">
						<view class="couponItems">
							<view class="ItemLeft">
								<view v-if="item.TypeCodeName === '兑换券'" class="itemName" style="background:#FFE6B2;">
									{{ item.TypeCodeName }}
								</view>
								<view v-if="item.TypeCodeName === '折扣券'" class="itemName" style="background:#FFCCB2;">
									{{ item.TypeCodeName }}
								</view>
								<view v-if="item.TypeCodeName === '优惠券'" class="itemName" style="background:#FFB2B2;">
									{{ item.TypeCodeName }}
								</view>
								<view v-if="item.TypeCodeName === '免排券'" class="itemName" style="background:#ffffb2;">
									{{ item.TypeCodeName }}
								</view>
								<view v-if="item.TypeCode === '1'" class="itemResult">
									<text>{{ _FormatNumber(item.deductionAmt) }}</text> 元
								</view>
								<view v-if="item.TypeCode === '2'" class="itemResult">
									<text>{{ item.Discounts }}</text> 折
								</view>
								<view v-if="item.TypeCode === '3'" class="itemResult">
									{{ item.GoodsName }}
								</view>
							</view>

							<view class="ItemRight">
								<view class="itemGoods">{{ item.TicketName }}</view>
								<view class="" style="display: flex;">
								<view class="itemDate">有效期：{{ item.EndData }}</view>
								</view>
								<view v-if="item.UseCondition === '1'" class="itemLimit">
									使用限制：每张桌台限用{{ item.RoomUseNum }}张
								</view>
								<view v-if="item.UseCondition === '2'" class="itemLimit">
									使用限制：会员每单消费可用{{ item.MemberUseNum }}张
								</view>
							</view>
						</view>

						<view v-if="item.IsNew && couponIndex === '0'" class="itemNew">新</view>

						<view :class="['couponCheckBox', !item.TypeState && 'couponTypeState']">
							<image :src="item.active ? iconData.couponed : iconData.coupon" mode="scaleToFill"
								:data-index="index" />
						</view>
					</view>
				</view>

				<view class="couponList" v-if="couponIndex == '1'">
				        <view class="couponItem "  v-for="(item, index) in couponNotList" :key="index" style="filter: grayscale(100%);">
				          <view class="couponItems" style="width: 100%;filter: grayscale(100%);min-height: 186rpx;">
				            <view class="ItemLeft" style="width: 180rpx;">
				              <view class="itemName">{{item.TypeCodeName}}</view>
							  <!-- 判断券类型显示不同内容 -->
				              <view class="itemResult " v-if="item.TypeCode == '1'">
				                <text>{{item.deductionAmt}}</text>
				                元
				              </view>
				              <view class="itemResult" v-if="item.TypeCode == '2'">
				                <text>{{item.Discounts}}</text>
				                折
				              </view>
				              <view class="itemResult" v-if="item.TypeCode == '3'">
				                {{item.GoodsName}}
				              </view>
				            </view>
				            <view class="ItemRight" style="width: 450rpx;">
				              <view class="itemGoods itemResultcolor">{{item.TicketName}}</view>
				              <view style="display: flex;">
				              <view class="itemDate">有效期：{{item.EndData}}</view>
				              </view>
							  <!-- 使用限制 -->
				              <view class="itemLimit" v-if="item.UseCondition == '1'">
				                使用限制：每张桌台限用{{item.RoomUseNum}}张
				              </view>
				              <view class="itemLimit" v-if="item.UseCondition == '2'">
				                使用限制：会员每单消费可用{{item.MemberUseNum}}张
				              </view>
				            </view>
				            <view class="itemNew" v-if="item.IsNew && couponIndex == '0'">新</view>
				          </view>
				        </view>
				      </view>
				
				<!-- 操作按钮 -->
				<view class="couponBtn">
					<view class="cancel" @click="cancel">取消</view>
					<view class="confirm" @click="confirm">确认</view>
				</view>
			</view>
		</view>
	</x-popup>
</template>

<script setup>
	import {
		ref,
		defineProps,
		defineEmits,
		toRef
	} from 'vue';
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app';
	import {
		HFiveMemberAppObjProcess
	} from '@/api/public.js'
	import wx from "weixin-js-sdk";
	import {
		rule_share,
		rule_amt,
		rule_count
	} from "./ticketRules";
	import { _FormatNumber } from '@/until/tools.js';
	
	const iconData = {
		coupon: "https://oss.jtmckj.com/wmp/images/common/i_checkbox_check.png",
		couponed: "https://oss.jtmckj.com/wmp/kbq/common/i_square_choose.png"
	}
	// 定义 props
	const props = defineProps({
		showUpgrade: {
			type: Boolean,
			default: false
		},
		payInfo: { // 支付相关信息
			type: Object,
			default: {}
		},
		info: { // 优惠券相关信息
			type: Object,
			default: {}
		},
		vipInfo: { // 是否享受权益价
			type: Boolean,
			default: false
		}
	});

	const payto = toRef(props.payto)
	const info = toRef(props.info)
	const payInfo = toRef(props.payInfo)
	const vipInfo = toRef(props.vipInfo)
	const couponNav = ref(["可使用优惠券", "不可用优惠券"])


	// 定义响应式数据
	const couponUseList = ref([]); // 已使用的优惠券列表
	const couponNotList = ref([]); // 未使用的优惠券列表
	const ticketUseList = ref([]); // 使用的票券
	const ticketUseTypeList = ref([]); // 票券类型列表
	const roomuselist = ref([]); // 房间使用列表
	const goodsTicketList = ref([]); // 商品票券列表
	const couponIndex = ref(0)
	const checkedList = ref([]) // 选中的优惠券数组（勾选优惠券时使用）
	const selectedCoupon = ref([]) // 传给父组件的选中的优惠券数组
	const userInfo = uni.getStorageSync('cardInfo')
	const cuoponPrice = ref(0) // 优惠券抵扣金额

	// 定义 emits
	const emit = defineEmits(['update:show', 'finishPay']);
	const {
		showUpgrade
	} = toRefs(props);
	// 关闭弹窗时触发的事件
	const closeUpgrade = (event) => {
		console.log(event);
		// emit('update:show', false);
	};
	const couponNavChange = (e) => {
		console.log(e);
		couponIndex.value = e
	}
	const couponAct = (e) => {
		console.log(e);
		const i = e



		// 判断如果是取消勾选就不进入之后的验证
		if (couponUseList.value[i].active) {
			couponUseList.value[i].active = !couponUseList.value[i].active;
			console.log(couponUseList.value);
			// 从checkedList中移除已取消的优惠券
			checkedList.value = checkedList.value.filter(item => item.Code !== couponUseList.value[i].Code);

			// 更新goodsTicketList
			goodsTicketList.value.forEach(v => {
				if (v.GoodsCode === couponUseList.value[i].GoodsCode) {
					v.orderQty += Number(couponUseList.value[i].GoodsCount);
					if (v.orderQty > 0) {
						v.isCanUseMore = true;
					}
				}
			});

			// 更新couponUseList
			couponUseList.value = [...couponUseList.value];

			return;
		}
		console.log(couponUseList.value);
		// 超出待付金额就不必再用券了
		let couponAmt = 0;
		couponUseList.value.forEach((e) => {
			if (e.active) {
				console.log(e.deductionAmt);
				couponAmt += e.deductionAmt;
			}
		});
		console.log(payInfo.value);
		if (vipInfo.value) { // 享受权益价
			if (payInfo.value.vipPriceTotal - payInfo.value.useGoldHad - payInfo.value.memberPayDiff - couponAmt <= 0) {
				uni.showToast({
					title: '待支付金额已经为0,无需再用优惠券',
					icon: "none",
				});
				return;
			}
		} else {
			if (payInfo.value.salePriceTotal - payInfo.value.useGoldHad - payInfo.value.memberPayDiff - couponAmt <= 0) {
				uni.showToast({
					title: '待支付金额已经为0,无需再用优惠券',
					icon: "none",
				});
				return;
			}
		}


		// 判断兑换券是否可用
		let duiFlag = false;
		goodsTicketList.value.forEach(v => {
			if (v.GoodsCode === couponUseList.value[i].GoodsCode && !v.isCanUseMore) {
				showToast({
					title: '兑换券使用数量已超出上限',
					icon: "none",
				});
				duiFlag = true;
			}
		});
		if (duiFlag) {
			return;
		}

		// 验证兑换券的使用
		goodsTicketList.value.forEach(v => {
			if (v.GoodsCode === couponUseList.value[i].GoodsCode) {
				v.orderQty -= Number(couponUseList.value[i].GoodsCount);
				if (v.orderQty <= 0) {
					v.isCanUseMore = false;
				}
			}
		});
		// 验证优惠共享
		const rule_share_res = rule_share(
			couponUseList.value[i],
			checkedList.value,
			roomuselist.value,
			vipInfo.value
		);

		if (!rule_share_res.flag) {
			uni.showToast({
				title: rule_share_res.errMsg,
				icon: "none",
			});
			return;
		}

		// 验证金额限制条件
		const rule_amt_res = rule_amt(
			couponUseList.value[i],
			checkedList.value,
			roomuselist.value,
			ticketUseList.value
		);

		if (!rule_amt_res.flag) {
			uni.showToast({
				title: rule_amt_res.errMsg,
				icon: "none",
			});
			return;
		}

		// 验证桌台或者会员使用数量
		const rule_count_res = rule_count(
			couponUseList.value[i],
			checkedList.value,
			ticketUseList.value,
			ticketUseTypeList.value
		);

		if (!rule_count_res.flag) {
			uni.showToast({
				title: rule_count_res.errMsg,
				icon: "none",
			});
			return;
		}

		// 更新优惠券使用状态
		couponUseList.value[i].active = !couponUseList.value[i].active;
		checkedList.value.push(couponUseList.value[i]);


		couponUseList.value = [...couponUseList.value];


	}


	const cancel = () => {
		emit('update:show', false);
	}
	// ------------------------------------------------------ 确认 ----------------------------------------------------------------


	const confirm = () => {
		let couponAmt = 0
		let arr = []
		let toolAllAmt = 0 // 计算用购物车总金额（折扣券时会变化）
		let carPrice = 0 // 购物车总金额（弹窗打开前就明确的，不会变化）
		if (vipInfo.value) { // 享受权益价
			toolAllAmt = payInfo.value.vipPriceTotal
			carPrice = payInfo.value.vipPriceTotal
		} else {
			toolAllAmt = payInfo.value.salePriceTotal
			carPrice = payInfo.value.salePriceTotal
		}
		
		couponUseList.value.forEach((e) => {
			if (e.active) { // 选择的优惠券
				if (e.TypeCode === '2') {
					// 多张折扣券的计算金额得在之前的基础上打折 如8折后的金额再打8折
					e.deductionAmt = Number(toolAllAmt) * (1 - (Number(e.Discounts) / 10))
					toolAllAmt = toolAllAmt - e.deductionAmt
				}

				couponAmt += e.deductionAmt
				arr.push(e)
			}
		})

		selectedCoupon.value = arr

		cuoponPrice.value = Number(couponAmt).toFixed(2)
		emit('update:show', false); // 关闭弹窗

		// 如果优惠券超出待支付金额，就让优惠券只抵扣待支付金额，并且不使用押金
		if (couponAmt >= carPrice) {
			cuoponPrice.value = Number(carPrice)
			payInfo.value.payBookAmt = 0
		} else { // 如果优惠券小于待支付金额，考虑押金
			if (couponAmt + payInfo.value.bookAmt >= carPrice) { // 如果优惠券加上押金大于待支付金额，押金仅取待支付金额和优惠券的差额
				cuoponPrice.value = Number(couponAmt).toFixed(2)
				payInfo.value.payBookAmt = Number(_FormatNumber(Number(carPrice) - Number(couponAmt)))
			} else { // 如果优惠券加上押金小于待支付金额，取优惠券金额和押金全部
				cuoponPrice.value = Number(couponAmt).toFixed(2)
				payInfo.value.payBookAmt = Number(payInfo.value.bookAmt)
			}
		}
		
		payInfo.value.ticketTotal = cuoponPrice.value 
		
		
		
		emit('finishPay', payInfo.value,selectedCoupon.value);
		// 使用优惠券时如果已经选中金币
		// if (data.selectedCoin) {
		// 	// 如果会员卡抵扣也被勾选上，要把会员卡抵扣清零（因为有先后顺序，先金币）
		// 	if (data.selectedMember) {
		// 		data.dikoAmt = 0
		// 	}
		// 	data.selectedCoin = false
		// 	data.coinsUsed = 0
		// 	const e = {
		// 		currentTarget: {
		// 			dataset: {
		// 				type: 'coin'
		// 			}
		// 		}
		// 	}
		// 	onSelect(e) // 选择金币
		// }

		// 使用优惠券时如果已经选中会员卡
		// if (data.selectedMember) {
		// 	data.selectedMember = false
		// 	data.dikoAmt = 0
		// 	const e = {
		// 		currentTarget: {
		// 			dataset: {
		// 				type: 'member'
		// 			}
		// 		}
		// 	}
		// 	onSelect(e) // 选择会员卡
		// }

	}


	onLoad((options) => {
		console.log(info.value,'dsadadadxxxxxxxxxxxxxxxxxxxxxx');
		const res = info.value
		// 在接收到数据后进行处理
		goodsTicketList.value = res.OrderStatistics;

		// 标记每个商品券是否可以多次使用
		goodsTicketList.value.forEach(v => {
			v.isCanUseMore = true;
		});

		let useList = [];
		let notList = [];

		res.TicketList.forEach((e) => {
			e.active = false;
			e.cheboxImg = "https://jtmc.oss-cn-hangzhou.aliyuncs.com/wmp/images/order/check0.png";
			e.TypeState = true;

			// 根据是否使用分为两组
			if (e.IsUse) {
				useList.push(e);
			} else {
				notList.push(e);
			}
		});

		// 更新响应式数据
		couponUseList.value = useList;
		couponNav.value[0] = `可使用优惠券(${couponUseList.value.length})`  
		couponNotList.value = notList;
		couponNav.value[1] = `不可用用优惠券(${couponNotList.value.length})`  
		ticketUseList.value = res.TicketUseList;
		ticketUseTypeList.value = res.TicketUseTypeList;
		roomuselist.value = res.roomuselist;
	});
</script>

<style scoped lang="less">
	.CouponBox {
		.couponContent {
			height: 1000rpx;
			background-color: var(--mainbaccolor10);
			position: absolute;
			left: 0;
			bottom: 0;
			width: 100%;
			border-radius: 32rpx 32rpx 0 0;

			.couponNav {
				display: flex;
				align-items: center;
				border-bottom: 1rpx solid var(--maincolorbd3);
				background: var(--mainbaccolor);
				border-radius: 48rpx 48rpx 0rpx 0rpx;

				.couponNavItem {
					width: 50%;
					text-align: center;

					.text {
						color: var(--maincolorf2);
						padding: 20rpx 0;
					}

					.line {
						height: 4rpx;
						width: 60rpx;
						// background-color: var(--mainbaccolor10);
						margin: auto;
					}
				}

				.couponNavItemA {
					position: relative;
					width: 50%;
					text-align: center;

					.text {
						font-weight: 700;
						color: var(--maincolorf1);
						padding: 20rpx 0;
					}

					.line {
						height: 4rpx;
						width: 60rpx;
						background-color: var(--mainbaccolor10);
						margin: auto;
					}
				}

				.couponNavItemA::before {
					content: '';
					position: absolute;
					bottom: 0rpx;
					left: 50%;
					transform: translateX(-50%);
					/* 将元素水平移动其自身宽度的一半，实现居中 */
					width: 60rpx;
					height: 4rpx;
					background: var(--mainbaccolor4);
					border-radius: 2rpx;
				}
			}

			

			.couponBtn {
				padding-top: 35rpx;
				height: 90rpx;
				display: flex;
				align-items: center;
				justify-content: center;

				view {
					padding: 18rpx 80rpx;
					border-radius: 60rpx;
					margin-right: 24rpx;
					font-size: 34rpx;
					font-weight: bold;
				}

				.cancel {
					color: var(--maincolorf2);
					border: 2rpx solid var(--maincolorbd5);
				}

				.confirm {
					color: var(--maincolor);
					background-color: var(--dt-backcolorPink);
				}
			}
		}
	}
	
	.couponList {
		height: 800rpx;
		overflow-y: scroll;
	
		.couponItem {
			position: relative;
			display: flex;
			align-items: center;
			background-image: url('https://oss.jtmckj.com/wmp/qnjg/coupon/i_card_dui-gay.png');
			background-size: 100% 100%;
			margin: 20rpx 26rpx;
			border-radius: 10rpx;
			overflow: hidden;
			box-sizing: border-box;
			// padding: 10rpx;
	
			.couponItems {
				position: relative;
				display: flex;
				align-items: center;
				width: 600rpx;
				height: 160rpx;
	
				border-radius: 18rpx;
				overflow: hidden;
	
				.ItemLeft {
					width: 170rpx;
	
					// 
					.itemName {
						position: absolute;
						top: 0;
						left: 0;
						text-align: center;
						width: 80rpx;
						height: 32rpx;
						line-height: 32rpx;
						background: var(--mainbaccolor6);
						border-radius: 16rpx 0rpx 16rpx 0rpx;
						font-family: PingFang SC;
						font-weight: 500;
						font-size: 20rpx;
						color: var(--maincolorf2);
					}
	
					.itemResult {
						text-align: center;
						color: var(--maincolorf5);
						font-size: 26rpx;
	
						text {
							font-size: 36rpx;
						}
					}
				}
	
				.ItemRight {
					width: 400rpx;
					box-sizing: border-box;
					padding: 0 20rpx;
	
					.itemDate {
						height: 36rpx;
						padding: 0 15rpx;
						line-height: 36rpx;
						background: var(--mainbaccolor3);
						font-size: 24rpx;
						color: var(--maincolorf4);
						margin-bottom: 10rpx;
					}
	
					.itemGoods {
						color: var(----maincolorf2) ;
						font-size: 30rpx;
						font-weight: bold;
						padding: 0 0 8rpx 0;
					}
	
					.itemLimit {
						color: var(--maincolorf4);
						font-size: 24rpx;
					}
				}
	
				.itemNew {
					position: absolute;
					top: 0;
					right: 0;
					background: linear-gradient(to right, #FF6A00, #E10119);
					color: var(--maincolor);
					font-size: 24rpx;
					padding: 0 14rpx;
					border-bottom-left-radius: 18rpx;
				}
			}
	
			.couponCheckBox {
				width: 70rpx;
				text-align: right;
	
				image {
					width: 36rpx;
					height: 36rpx;
				}
			}
	
			.couponTypeState image {
				background-color: var(--maincolorf2);
				pointer-events: none;
			}
		}
	
		.couponItemcanbus {
			background-image: url(https://oss.jtmckj.com/wmp/qnjg/coupon/i_card_dui.png) !important;
			background-size: 100% 100% !important;
	
			.ItemLeft {
				.itemName {
					font-weight: 500;
					font-size: 20rpx;
					color: var(----maincolorf1) !important;
				}
			}
	
			.itemDate {
				background: var(--mainbaccolor17) !important;
				color: var(--maincolorf3) !important;
			}
	
			.itemGoods {
				color: var(--maincolorf4) ;
			}
	
			.itemNew {
				position: absolute;
				top: 0;
				right: 0;
				background: linear-gradient(to right, #FF6A00, #E10119);
				color: var(--maincolor);
				font-size: 24rpx;
				padding: 0 14rpx;
				border-bottom-left-radius: 18rpx;
			}
		}
	}
	.itemResultcolor{
		color: var(--maincolorf2) !important;
	}
</style>